package org.sixtythousand.joker.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.sixtythousand.joker.AbstractConnector;
import org.sixtythousand.joker.ConnectionFactory;
import org.sixtythousand.joker.handler.Handler;
import org.sixtythousand.joker.handler.HandlerManager;
import org.sixtythousand.joker.Server;

import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.Executor;

/**
 * @author zhoulk
 * @date 2023/10/11 12:04
 * @desc
 */
public class NettyServerConnector extends AbstractConnector {

    protected ServerBootstrap serverBootstrap;
    protected ServerSocketChannel serverSocketChannel;
    protected EventLoopGroup bossGroup = new NioEventLoopGroup();
    protected EventLoopGroup workerGroup = new NioEventLoopGroup();
    protected ConnectionFactory connectionFactory = new NettyConnectionFactory();
    protected NettyConnectionManager connectionManager;
    protected HandlerManager handlerManager;
    protected ServerBootstrap bootstrap;
    protected Handler handler;

    public NettyServerConnector(Integer port, Server server, Executor executor, Handler handler, ConnectionFactory... factories) {
        super(server, executor, factories);
        this.port = port;
        this.handler = handler;
        connectionManager = new NettyConnectionManager(this, connectionFactory, handler);
    }


    @Override
    public void doStart() {
        // todo 测试阶段先凑合用
        try {
            bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("http-codec", new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                            pipeline.addLast("acceptor", new NettyAcceptHandler());
                            ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        }
                    });
            Channel ch = bootstrap.bind(port).sync().channel();
            System.out.println("Web Socket server started at port" + port + ".");
            ch.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    protected void accept(Integer id) {

    }

    private void accepted(ChannelHandlerContext context) {
        connectionManager.onAccept(context);
    }

    public class NettyAcceptHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            accepted(ctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("read");
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;

            connectionManager.onRead(ctx, fullHttpRequest);
        }
    }
}
